﻿using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace PADWH35
{
    public partial class setDept : Form
    {
        public setDept()
        {
            InitializeComponent();          
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            string sql = "  SELECT DISTINCT [Description]+'-'+JCDept name,JCDept,[Description] FROM Erp.JCDept WHERE Company='NSZ'";
            DataTable dt = DBHelper.ExecuteDt(sql);
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "name";
            comboBox1.ValueMember = "JCDept";
            comboBox1.Text = GetConfig("dept_");
        }

        public void SaveConfig(string value, string name)
        {
            XmlDocument doc = new XmlDocument();
            //获得配置文件的全路径  
            string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;//AppDomain.CurrentDomain.BaseDirectory.ToString() + ".exe.config";
            doc.Load(strFileName);
            //找出名称为“add”的所有元素  
            XmlNodeList nodes = doc.GetElementsByTagName("add");
            for (int i = 0; i < nodes.Count; i++)
            {
                //获得将当前元素的key属性  
                XmlAttribute att = nodes[i].Attributes["name"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素  
                if (att.Value == name)
                {
                    //对目标元素中的第二个属性赋值  
                    att = nodes[i].Attributes["connectionString"];
                    att.Value = value;
                    break;
                }
            }
            //保存上面的修改  
            doc.Save(strFileName);
        }
        public static string GetConfig(string name)
        {
            string value = null;
            XmlDocument doc = new XmlDocument();
            //获得配置文件的全路径
            string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;//AppDomain.CurrentDomain.BaseDirectory.ToString() + ".exe.config";
            doc.Load(strFileName);
            //找出名称为“add”的所有元素
            XmlNodeList nodes = doc.GetElementsByTagName("add");
            for (int i = 0; i < nodes.Count; i++)
            {
                //获得将当前元素的key属性  
                XmlAttribute att = nodes[i].Attributes["name"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素  
                if (att.Value == name)
                {
                    //对目标元素中的第二个属性赋值  
                    att = nodes[i].Attributes["connectionString"];
                    value = att.Value;
                    break;
                }
            }
            //保存上面的修改  
            return value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SaveConfig(comboBox1.Text.ToString(), "dept_");
                MessageBox.Show("修改成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }
    }
}
